package pl.edu.agh.io.sylvia.entity;

import java.io.BufferedReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Article extends DBObject {

	private static final String MESSAGE_ID = "Message-ID";

	private String header;
	private String body;
	private Group group;
	private List<Monitor> monitors = new ArrayList<Monitor>();

	public Article(Integer id, String header, String body, Group group, List<Monitor> monitors) {
		super(id);
		this.header = header;
		this.body = body;
		this.group = group;
		this.monitors = monitors;
	}

	public Group getGroup() {
		return group;
	}

	public void setGroup(Group group) {
		this.group = group;
	}

	public List<Monitor> getMonitors() {
		return monitors;
	}

	public void setMonitors(List<Monitor> monitors) {
		this.monitors = monitors;
	}

	public String getHeader() {
		return header;
	}

	public void setHeader(String header) {
		this.header = header;
	}

	public String getBody() {
		return body;
	}

	public void setBody(String body) {
		this.body = body;
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof Article) {
			if ((((Article) obj).id != null) && (id != null)) {
				return super.equals(obj);
			} else {
				return getMessageId().equals(((Article) obj).getMessageId());
			}
		} else {
			return super.equals(obj);
		}
	}
	
	@Override
	public int hashCode() {
		return getMessageId().hashCode();
	}

	private String getMessageId() {
		Map<String, String> map = readHeader(new StringReader(header));
		return map.get(MESSAGE_ID);
	}

	private Map<String, String> readHeader(Reader reader) {
		HashMap<String, String> map = new HashMap<String, String>();
		BufferedReader bufferedReader = new BufferedReader(reader);
		String line;
		try {
			while((line = bufferedReader.readLine()) != null) {
				Pattern pattern = Pattern.compile("(.*): (.*)");
				Matcher matcher = pattern.matcher(line);
				if (matcher.matches()) {
					System.out.println(matcher.group(1) + ": " + matcher.group(2));
					map.put(matcher.group(1), matcher.group(2));
				}
			}
		} catch (Exception e) {
		}
		return map;
	}
}
